import 'dart:async';
import 'dart:typed_data';

import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rider/app.dart';
import 'package:flutter_rider/event/show_operator_info_event.dart';
import 'package:flutter_rider/generated/assets.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/kit/loc_kit.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/main/widgets/pop/pop_operator_info.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/module/mine/api/user_api.dart';
import 'package:flutter_rider/module/mine/models/operator_model.dart';
import 'package:flutter_rider/module/mine/provider/mine_provider.dart';
import 'package:flutter_rider/module/mine/provider/outside_car_provider.dart';
import 'package:flutter_rider/routers/fluro_navigator.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/config.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';

class OperatorManagePage extends ConsumerStatefulWidget {
  const OperatorManagePage({Key? key}) : super(key: key);

  @override
  ConsumerState createState() => _OperatorManagePagePageState();
}

class _OperatorManagePagePageState extends ConsumerState<OperatorManagePage> {
  final StateLayoutController _stateLayoutController = StateLayoutController();
  final _initMarkerMap = <String, Marker>{};
  late List<OperatorModel> _operatorList;

  AMapController? _mapController;

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  OperatorModel? _selectOperatorModel;

  late StreamSubscription _eventFn;

  var _isShowPopOperatorInfoEvent = false;

  @override
  void initState() {
    super.initState();
    _eventFn = eventBus.on<ShowPopOperatorInfoEvent>().listen((event) {
      setState(() {
        _isShowPopOperatorInfoEvent = event.isShowPopOperatorInfo;

        if (!_isShowPopOperatorInfoEvent) {
          print("object + ${event.isShowPopOperatorInfo}");
          _selectOperatorModel?.isSelect = false;
          _renderMarkerMap();
        }
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _mapController?.disponse();
    _eventFn.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: UIColor.color_main,
      floatingActionButton: _renderResetLoc(),
      // floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      body: SafeArea(
        top: false,
        bottom: false,
        child: StateLayout(
            url: UserApi.getLocation,
            controller: _stateLayoutController,
            childBuilder: _renderContent,
            dataCallback: _dataCallback),
      ),
    );
  }

  _dataCallback(dynamic data) async {
    List list = data as List;
    _operatorList = list.map((e) => OperatorModel.fromJson(e)).toList();
    _renderMarkerMap();
  }

  ///渲染操作员信息
  _renderMarkerMap() async {
    for (var item in _operatorList) {
      if (item.lat.isEmpty || item.lng.isEmpty) continue;

      ByteData? byteData = await App.widgetToByteData(widgetContext(item));
      var icon = BitmapDescriptor.fromBytes(byteData!.buffer.asUint8List());
      var marker = Marker(
          position: LatLng(double.parse(item.lat), double.parse(item.lng)),
          icon: icon,
          infoWindow:
              InfoWindow(title: "lat：${item.lat}", snippet: "lng：${item.lng}"),
          infoWindowEnable: false,
          onTap: (e) {
            _scaffoldKey.currentState?.showBottomSheet(
              (context) => StatefulBuilder(builder: (context, state) {
                return PopOperatorInfo(item);
              }),
              backgroundColor: Colors.transparent,
            );

            Future.delayed(const Duration(milliseconds: 100), () {
              _selectOperatorModel?.isSelect = false;
              _selectOperatorModel = item;
              _selectOperatorModel?.isSelect = true;
              _renderMarkerMap();
              //延迟下，等上次的弹框 dispose 再 刷新
            });
          });

      _initMarkerMap[item.Id.toString()] = marker;
    }
    setState(() {});
  }

  ///自定义widget
  widgetContext(OperatorModel operatorModel) {
    return Container(
        height: 280.rpx,
        width: 280.rpx,
        decoration: BoxDecoration(
          // border: Border.all(width: 1.rpx, color: UIColor.color_primary),
          image: DecorationImage(
            image: AssetImage(operatorModel.isSelect
                ? Assets.imageMarkBgH
                : Assets.imageMarkBgN),
            fit: BoxFit.fitWidth, // 完全填充
          ),
        ),
        child: Column(children: [
          Container(
            padding: EdgeInsets.all(20.rpx),
            height: 140.rpx,
            width: 280.rpx,
            alignment: Alignment.center,
            child: Text(
              operatorModel.name,
              style: TextStyle(
                  color: operatorModel.isSelect
                      ? Colors.white
                      : UIColor.color_black,
                  fontSize: 38.rpx),
              textDirection: TextDirection.ltr,
            ),
          ),
        ]));
  }

  Widget _renderContent(dynamic data) {
    return Stack(
      children: [
        _renderMap(),
        Positioned(
            top: ScreenUtil.getInstance().statusBarHeight,
            left: 16.rpx,
            child: GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              // child:
              // Container(
              // height: 60.rpx,
              // width: 60.rpx,
              // margin: EdgeInsets.all(28.rpx),
              child: SvgPicture.asset(
                R.image_chevron_left,
                width: 50.rpx,
                height: 50.rpx,
                // ),
              ),
            )),
      ],
    );
  }

  Widget _renderMap() {
    var lat = "0.0";
    var lng = "0.0";
    LatLng position = const LatLng(0, 0);
    var result = LocKit.instance.getData();
    if (result.containsKey('latitude') && result.containsKey('longitude')) {
      lat = result["latitude"].toString();
      lng = result["longitude"].toString();
      position = LatLng(double.parse(lat), double.parse(lng));
    } else {
      position = const LatLng(22.532785, 113.946690);//如果没有拿到定位经纬度，默认定位到深圳软件园T3
    }

    return AMapWidget(
      apiKey: const AMapApiKey(
          androidKey: Config.androidAmapKey, iosKey: Config.iOSAmapKey),
      onMapCreated: _onMapCreated,
      privacyStatement: const AMapPrivacyStatement(
          hasContains: true, hasShow: true, hasAgree: true),
      initialCameraPosition: CameraPosition(target: position),
      //initialCameraPosition: CameraPosition(target: LatLng(22.560857, 114.039319)),

      markers: Set<Marker>.of(_initMarkerMap.values),
      // polylines: Set<Polyline>.of(_polylines.values),
      buildingsEnabled: false,
      labelsEnabled: false,
      // scrollGesturesEnabled: widget.isAddCar,
      myLocationStyleOptions: MyLocationStyleOptions(
        true,
        circleFillColor: Colors.transparent,
        circleStrokeColor: Colors.blue,
        circleStrokeWidth: 1,
        //根据输入的icon路径[iconPath]创建[BitmapDescriptor]定位小蓝点
        // icon: BitmapDescriptor.fromIconPath("assets/images/****.png"),
      ),
      // // onCameraMove: (position) {
      // //   Log.i(position.toString());
      // // },
      onCameraMoveEnd: (position) {},
    );
  }

  _onMapCreated(AMapController controller) {
    setState(() {
      _mapController = controller;
      _moveToPosition();
    });
  }

  _moveToPosition() {
    LatLng position;
    var lat = "0.0";
    var lng = "0.0";
    var result = LocKit.instance.getData();
    if (result.containsKey('latitude') && result.containsKey('longitude')) {
      lat = result["latitude"].toString();
      lng = result["longitude"].toString();
      position = LatLng(double.parse(lat), double.parse(lng));
    } else {
      position = const LatLng(22.532785, 113.946690);//如果没有拿到定位经纬度，默认定位到深圳软件园T3
    }

    _mapController?.moveCamera(
      CameraUpdate.newCameraPosition(
        CameraPosition(target: position, zoom: 16, tilt: 0, bearing: 0),
      ),
      animated: true,
    );
  }

  Widget _renderResetLoc() {
    // return Consumer(builder: (context, ref, child) {
    return Padding(
        padding: EdgeInsets.only(
            bottom: _isShowPopOperatorInfoEvent ? 80.rpx : 0.rpx),
        child: FloatingActionButton(
          onPressed: () {
            setState(() {});
            _moveToPosition();
          },
          backgroundColor: UIColor.color_content,
          child: Container(
            padding: EdgeInsets.all(10.rpx),
            // decoration: BoxDecoration(
            //   color: UIColor.color_content,
            //   borderRadius: BorderRadius.all(Radius.circular(8.rpx)),
            // ),
            child: Icon(Icons.my_location_sharp,
                size: 24.rpx, color: const Color(0xff54BD95)),
          ),
        ));
    // }
    // );
  }
}
